<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { Octokit } from 'octokit'
import axios from 'axios'
import {
  Layout as TinyLayout,
  Row as TinyRow,
  Col as TinyCol,
  Grid as TinyGrid,
  GridColumn as TinyGridColumn,
  Modal
} from '@opentiny/vue'
import { fakeDatas } from '../fake-data'

const octokit = new Octokit({
  auth: ''
})

const starCount = ref(0)
const forkCount = ref(0)

const tableData: {
  name: string
  star: string | number
  fork: number
}[] = reactive([])

onMounted(async () => {
  let allDatas

  try {
    const fetchTinyVue = octokit.request('GET /repos/opentiny/tiny-vue')
    const fetchTinyEngine = octokit.request('GET /repos/opentiny/tiny-engine')
    const fetchTinyNG = octokit.request('GET /repos/opentiny/ng')
    const fetchTinyCLI = octokit.request('GET /repos/opentiny/tiny-cli')
    allDatas = await axios.all([fetchTinyVue, fetchTinyEngine, fetchTinyNG, fetchTinyCLI])
  } catch(e) {
    Modal.message(`后台接口出错，将使用 ${fakeDatas.date} 的数据，错误信息：${e}`)
    allDatas = fakeDatas.data
  }

  allDatas.forEach(({ data }) => {
    const { name, stargazers_count, forks_count } = data
    
    starCount.value += stargazers_count
    forkCount.value += forks_count

    tableData.push({
      name,
      star: stargazers_count >= 1000 ? `⭐${stargazers_count}` : stargazers_count,
      fork: forks_count,
    })
  })
})
</script>

<template>
  <h3>概览数据</h3>
  <tiny-layout>
    <tiny-row>
      <tiny-col :span="6">
        <el-statistic title="Star" :value="starCount" />
      </tiny-col>
      <tiny-col :span="6">
        <el-statistic title="Fork" :value="forkCount" />
      </tiny-col>
    </tiny-row>
  </tiny-layout>
  <h3>详情数据</h3>
  <tiny-grid :data="tableData" border>
    <tiny-grid-column field="name" title="项目"></tiny-grid-column>
    <tiny-grid-column field="star" title="Star"></tiny-grid-column>
    <tiny-grid-column field="fork" title="Fork"></tiny-grid-column>
  </tiny-grid>
</template>

<style scoped>

</style>
